import request from './request'

// 用户登录
export interface LoginRequest {
  username?: string
  email?: string
  phone?: string
  password: string
}

export interface LoginResponse {
  code: number
  message: string
  data: {
    token: string
    userInfo: {
      userId: number
      username: string
      email: string
      phone: string
      nickname: string
      avatar?: string
      gender?: number
      status: number
      lastLoginAt?: string
    }
  }
}

// 用户注册
export interface RegisterRequest {
  username?: string
  email?: string
  phone?: string
  password: string
  nickname?: string
}

// 用户信息
export interface UserInfo {
  userId: number
  username: string
  email: string
  phone: string
  nickname: string
  avatar?: string
  gender?: number
  status: number
  lastLoginAt?: string
  createdAt?: string
  updatedAt?: string
}

// 注册响应
export interface RegisterResponse {
  code: number
  message: string
  data: {
    token: string
    userInfo: UserInfo
  }
}

export const userApi = {
  // 用户登录
  login: (data: LoginRequest) => {
    return request.post<LoginResponse>('/api/auth/login', data)
  },

  // 用户注册
  register: (data: RegisterRequest) => {
    return request.post<RegisterResponse>('/api/auth/register', data)
  },

  // 获取用户信息
  getUserInfo: () => {
    return request.get<{code: number, message: string, data: UserInfo}>('/api/auth/profile')
  },

  // 更新用户信息
  updateUserInfo: (data: Partial<UserInfo>) => {
    return request.put('/api/auth/profile', data)
  },

  // 更新用户资料（新增方法，用于Profile页面）
  updateProfile: (userId: number, data: Partial<UserInfo>) => {
    return request.put<{code: number, message: string, data: UserInfo}>(`/api/users/${userId}`, data)
  },

  // 修改密码
  changePassword: (data: { oldPassword: string; newPassword: string }) => {
    return request.post('/api/auth/change-password', data)
  },

  // 上传头像
  uploadAvatar: (file: File) => {
    const formData = new FormData()
    formData.append('avatar', file)
    return request.post<{code: number, message: string, data: {url: string}}>('/api/upload/avatar', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })
  }
}